package org.logMonitor.utils;

import net.sf.json.JSONException;
import org.json.JSONObject;
import org.logMonitor.dto.CityLngLat;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lenovo on 2018/1/21.
 * 蒙的密钥：akZILvuv0Ovr6uU3eKlaXP2Pgx9jprjO
 * 通过ip得到所在城市,以及城市所在经纬度坐标
 */
public class AddressUtilsBaidu {
    public static CityLngLat getAddrName(String ip)  {
        try{
            //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
            JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg&ip="+ip+"&coor=bd09ll");
        /* 获取到的json对象：
         *         {"address":"CN|河北|保定|None|UNICOM|0|0",
         *        "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307},
         *        "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}},
         *        "status":0}
        */

            JSONObject content=json.getJSONObject("content");              //获取json对象里的content对象
            JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail
            String city=addr_detail.get("city").toString();                //获取市名，可以根据具体需求更改，如果需要获取省份的名字，可以把“city”改成“province”...
            JSONObject point=content.getJSONObject("point");//从content对象里获取point经纬度
            String x=point.get("x").toString();//从point对象里获取x经度
            String y=point.get("y").toString();//从point对象里获取y纬度
            CityLngLat cityLngLat = new CityLngLat(city, new Double[]{Double.valueOf(x),Double.valueOf(y)});
            return cityLngLat;
        }catch (Exception e){
            CityLngLat cityLngLat = new CityLngLat("保定", new Double[]{115.48,38.85});
            return cityLngLat;
        }

    }
    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            //关闭输入流
            is.close();
        }
    }
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }


    public static void main(String[] args) throws IOException, JSONException {
        //System.out.println(getAddrName("192.168.2.112"));
//       System.out.println(getAddrName("122.49.20.247"));
        System.out.println(getAddrName("183.203.65.19"));
    }


}
